import React from 'react';
import { Button, Form, Input, Checkbox,Tree,Row,Col, TreeSelect,message  } from 'antd';
import { injectIntl } from 'react-intl';
import axios from 'axios';
import SCSelect from '../../components/pickCity/SCSelect';

const FormItem = Form.Item;
const createForm = Form.create;
const TreeNode = Tree.TreeNode;


class divisionManagement extends React.Component {
    constructor(props){
        super(props);
        this.common = this.props.intl.messages.common;
        this.state={
            expandedKeys: [],
            autoExpandParent: true,
            selectedKeys: [],
            curDepartment:{},
            departmentTree:[],
        }
    }


    componentWillMount(){
        this.fetchApi()
    }

    fetchApi=()=>{
        axios.get('/api/org/list/qry',{loading:true}).then(res => {
            if (res && res.code == 200) {
                var arr4Level=res.data.map(k=>k.level);
                var min=Math.min(...arr4Level);
                res.data.forEach(ele=>{
                    let parentId = ele.parentOrgId;
                    ele.title= ele.name;
                    ele.key= ele.id;
                    ele.value= ele.id;
                    let level = ele.level;
                    if(level!=min){
                        res.data.forEach(d=>{
                            if (d.id === parentId) {
                                let childArray = d.children;
                                if(!childArray){
                                    childArray = []
                                }
                                childArray.push(ele);
                                d.children = childArray;
                            }
                        })
                    }
                });
                let data = res.data.filter(ele => ele.level == min);
                console.log('最终等到的tree结构数据: ', data);
                this.setState({
                    departmentTree:data
                })
            }
        })
    };


    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!!err) {
                console.log('Received values of form: ', values);
                return;
            }
            values.type=values.type?1:0;
            let flag=this.state.selectedKeys.length>0?true:false;
            if(flag){
                values.id=this.state.curDepartment.id;
                axios.get('/api/org/mod',{params:{...values},loading:true}).then(res=>{
                    if(res&&res.code==200){
                        message.success('操作成功');
                        this.fetchApi();
                    }
                })
            }else{
                axios.get('/api/org/add',{params:{...values},loading:true}).then(res=>{
                    if(res&&res.code==200){
                        message.success('操作成功');
                        this.fetchApi();
                    }
                })
            }
        });
    };

    onExpand = (expandedKeys) => {
        console.log('onExpand', expandedKeys);
        this.setState({
            expandedKeys,
            autoExpandParent: false,
        },()=>{});
    };

    resetPass=()=>{
        axios.get('api/corp/psw/reset', {params:{id:this.state.curDepartment.ownerId},loading:true}).then(res => {
            if (res && res.code==200) {
                if (res.data == 1) {
                    message.success(`${this.common.resetPasswordSuc},密码123456`);
                }
                if (res.data == 0) {
                    message.error(this.common.resetPasswordFailure);
                }
            }
        })
    };

    deleteDep=()=>{
        axios.get('/api/org/mod', {params:{id:this.state.curDepartment.id,status:9},loading:true}).then(res => {
            if (res && res.code==200) {
                message.success('操作成功');
                this.fetchApi();
            }
        })
    };


    onSelect = (selectedKeys, info) => {
        console.log('onSelect', info);
        this.props.form.resetFields();
        this.setState({ selectedKeys,
            curDepartment:info.node.props.dataRef||info.node.props
        },()=>{console.log(this.state)});
    };

    renderTreeNodes = (data) => {
        return data.map((item) => {
            if (item.children) {
                return (
                    <TreeNode title={item.title} key={item.key} dataRef={item}>
                        {this.renderTreeNodes(item.children)}
                    </TreeNode>
                );
            }
            return <TreeNode {...item} />;
        });
    };



    render(){
        const {getFieldDecorator} = this.props.form;
        const formItemLayout = {
            labelCol: {
                xl: { span: 6 },
            },
            wrapperCol: {
                xl: { span: 16 },
            },
        };
        const tailFormItemLayout = {
            wrapperCol: {
                xl: {
                    span: 18,
                    offset: 6,
                },
            },
        };
        let flag=this.state.selectedKeys.length>0?true:false;
        console.log('flag',flag);
        return(
            <Row gutter={16}>
                <Col xl={4} xxl={3}>
                    <Button type={'primary'} onClick={()=>{ this.props.form.resetFields();this.setState({selectedKeys:[]})}} style={{margin:'10px 0px 20px'}}>新增部门</Button>
                    <Tree
                        onExpand={this.onExpand}
                        expandedKeys={this.state.expandedKeys}
                        autoExpandParent={this.state.autoExpandParent}
                        onSelect={this.onSelect}
                        selectedKeys={this.state.selectedKeys}
                        defaultExpandAll={true}
                    >
                        {this.renderTreeNodes(this.state.departmentTree)}
                    </Tree>
                </Col>
                <Col xl={10} xxl={8} className={'line'}>
                    <div style={{textAlign:'center',margin: '10px 0 20px 0'}}>{flag?'修改部门信息':'新增部门'}</div>
                    <form form={this.props.form}>
                        <FormItem
                            {...formItemLayout}
                            label={this.common.departmentName}
                        >
                            {getFieldDecorator('name',{
                                rules: [
                                    {
                                        required: true,
                                        message: this.common.required
                                    }
                                ],
                                initialValue:flag?this.state.curDepartment.name:undefined
                            })(
                                <Input />
                            )}
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label={this.common.superDepartment}
                        >
                            {getFieldDecorator('parentOrgId',{
                                initialValue:flag?this.state.curDepartment.parentOrgId:undefined
                            })(
                                <TreeSelect
                                    dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                                    treeData={this.state.departmentTree}
                                    allowClear={true}
                                />
                            )}
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label={this.common.linkman}
                        >
                            {getFieldDecorator('accountName',{
                                initialValue:flag?this.state.curDepartment.accountName:undefined
                            })(
                                <Input/>
                            )}
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label={this.common.linkPhone}
                        >
                            {getFieldDecorator('phone',{
                                initialValue:flag?this.state.curDepartment.phone:undefined
                            })(
                                <Input />
                            )}
                        </FormItem>
                        <FormItem
                            {...tailFormItemLayout}
                            style={{whiteSpace:'nowrap'}}
                        >
                            {getFieldDecorator('type',{
                                valuePropName: 'checked',
                                initialValue:flag&&this.state.curDepartment.type==1?true:undefined
                            })(
                                <Checkbox>{this.common.TIPS}:123456</Checkbox>
                            )}
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                        >
                            {getFieldDecorator('isDiscount',{
                                
                            })(
                                <SCSelect data={[{id:0,name:'部门折扣优先'},{id:1,name:'部门折扣优先'}]}/>
                            )}
                        </FormItem>
                        

                        <FormItem {...tailFormItemLayout}>
                            {flag&&<Button  style={{marginRight:8,width:'45%'}} onClick={this.resetPass}>{this.common.resetPassword}</Button>}
                            <Button type="primary" htmlType="submit" onClick={this.handleSubmit} style={{width:'45%'}}>{this.common.sure}</Button>
                        </FormItem>
                        <FormItem {...tailFormItemLayout}>
                            {flag&&<Button  type="danger" style={{width:'92%'}} onClick={this.deleteDep}>{'删除部门'}</Button>}
                        </FormItem>
                    </form>
                </Col>
            </Row>

        )
    }
}


divisionManagement=createForm()(divisionManagement);
export default injectIntl(divisionManagement);